package org.marsdonne.monitring_agent

import groovy.json.JsonOutput
import groovy.json.JsonSlurper
import okhttp3.MediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import org.apache.http.NameValuePair
import org.apache.http.client.utils.URLEncodedUtils
import org.apache.http.message.BasicNameValuePair
import org.springframework.boot.context.properties.ConfigurationProperties

@ConfigurationProperties("reporter")
class Reporter {

    String corpId
    String corpSecret
    Integer agentId

    List<String> recipients

    private Date dateRequested
    private String accessToken
    private Integer expiredSeconds
    private Integer reRequestCounter = 0

    String auth() {
        if (null == dateRequested || null == expiredSeconds || new Date().getTime() - dateRequested.getTime() > (expiredSeconds - 10) * 1000) {
            def url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$corpId&corpsecret=$corpSecret"

            def request = new Request.Builder().url(url).get().build()

            try {
                dateRequested = new Date()
                def client = new OkHttpClient()
                def response = client.newCall(request).execute()

                Map jsonResp = new JsonSlurper().parseText(response.body().string())

                accessToken = jsonResp.access_token
                expiredSeconds = jsonResp.expires_in

                reRequestCounter++
            } catch (Exception e) {
                println "企业微信认证失败：$e.message"
            }
        }

        return accessToken
    }

    /**
     * async
     */
    void send(String title, String content, String description) {
        println "\n\n$title\n$content\n$description"

        String access_token = this.auth()

        String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=$access_token"

        def message = [
                touser: recipients.join(","), msgtype: "text", agentid: this.agentId, safe: 0,
                text  : [content: "$title\n$content\n$description"]
        ]

        httpPost(url, message, true)
    }

    private void httpPost(String url, Map message, Boolean payloadIsJson) {
        RequestBody body

        if (payloadIsJson) {
            body = RequestBody.create(PayloadType.JSON.getMediaType(), JsonOutput.toJson(message))
        } else {
            List<NameValuePair> params = new LinkedList<>()
            for (Map.Entry<String, String> entry : message.entrySet()) {
                params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()))
            }
            body = RequestBody.create(PayloadType.STRING.getMediaType(), URLEncodedUtils.format(params, "ascii"))
        }

        Request request = new Request.Builder().url(url).post(body).build()
        try {
            new OkHttpClient().newCall(request).execute()
        } catch (Exception e) {
            println "企业微信接口[$url]调用失败：$e.message"
        }
    }

    private enum PayloadType {
        JSON(MediaType.parse("application/json charset=utf-8")),
        STRING(MediaType.parse("application/x-www-form-urlencoded charset=utf-8"))

        private MediaType mediaType

        PayloadType(MediaType mediaType) {
            this.mediaType = mediaType
        }

        MediaType getMediaType() {
            return mediaType
        }
    }
}
